/*
 * @Author: szx
 * @Date: 2021-11-09 13:46:04
 * @LastEditTime: 2021-11-09 14:07:13
 * @Description:
 * @FilePath: \leetcode\200-299\235\235.cpp
 */
#include <iostream>
using namespace std;
struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right)
        : val(x), left(left), right(right) {}
};

class Solution {
   public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (!root) return;
        if (root->val >= p->val && root->val <= q->val) {
            return root;

        } else if (root->val >= p->val && root->val >= q->val) {
            lowestCommonAncestor(root->left, p, q);
        } else if (root->val <= p->val && root->val <= q->val) {
            lowestCommonAncestor(root->right, p, q);
        }
        return nullptr;
    }
};
